#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@IDE     ：PyCharm 
@Author  ：kiway
@Date    ：2024/5/3 10:42 
"""

from .BaseEngine import BaseEngine
import ccxt.pro
import pandas as pd
import traceback
import multiprocessing
import asyncio
from ..config import config
import time
from .DataPersist import BalanceRecord, PositionRecord, LatestRecord

exchange = getattr(ccxt.pro, config.exchange_id)({
    'options': config.exchange_options,
    'apiKey': config.exchange_apikey,
    'secret': config.exchange_secret,
})

exchange.set_sandbox_mode(config.sandbox_mode)


class AccountEngine(BaseEngine):

    def __init__(self, main_engine):
        super().__init__("账户引擎", main_engine)
        self._holding_positions_df = None
        self._account_balance_df = None

    def write(self, data_evn, data: str, sid=None):
        if sid is None:
            sid = str(int(time.time() * 1000))

        data_evn.insert(sid, data)

    async def fetch_account_balance(self, ev):
        """记录账户余额信息"""
        count = 0
        record_evn_latest = LatestRecord()

        while True:
            try:
                data = await exchange.fetch_balance_ws(params={"method": "account.balance"})
                self.write(record_evn_latest, str(data), sid="latest_balance")
                if count == 0:
                    ev.set()
                    count += 1

            except Exception as e:
                traceback.print_exc()

    async def fetch_account_info(self, market_type="future"):
        """记录账户余额信息"""

        try:
            balance = await exchange.fetch_balance(params={"type": market_type})
            return balance

        except Exception as e:
            traceback.print_exc()

    async def fetch_holding_positions(self):
        # 获取合约的持仓信息

        record_evn_pos = PositionRecord()
        record_evn_latest = LatestRecord()

        while True:
            try:
                data = await exchange.fetch_positions_ws()

                if data:
                    self.write(record_evn_pos, str(data), sid=None)

                    self.write(record_evn_latest, str(data), sid="latest_pos")

                # self.main_engine.put_event(
                #     PositionsEvent(data=self._holding_positions_df))

            except Exception as e:
                traceback.print_exc()

    async def record_account_balance(self):
        """获取账户历史成交信息"""

        record_evn_balance = BalanceRecord()

        while True:
            data = await self.fetch_account_info()
            if data:
                self.write(record_evn_balance, str(data))
            await asyncio.sleep(100)

    def _start(self):
        ev = multiprocessing.Event()
        p = multiprocessing.Process(target=self._run, args=(ev,))
        p.start()
        ev.wait()

    def _run(self, ev):
        loop = asyncio.new_event_loop()
        t1 = loop.create_task(self.fetch_holding_positions())
        t3 = loop.create_task(self.fetch_account_balance(ev))
        t2 = loop.create_task(self.record_account_balance())
        loop.run_until_complete(asyncio.wait([t1, t2, t3]))
